// api/summaryApi.ts
import api from './config';
import type { POSTResponse } from '../../types/api';

/**
 * 创建海运（SEA）招标汇总文件
 */
export const createSeaSummary = async (tenderId: string): Promise<POSTResponse> => {
  const response = await api.post<POSTResponse>(`/tenders/${tenderId}/summaries/sea`, null);
  return response.data;
};

/**
 * 创建 PP管件 招标汇总文件
 */
export const createPipeSummary = async (tenderId: string): Promise<POSTResponse> => {
  const response = await api.post<POSTResponse>(`/tenders/${tenderId}/summaries/pipe`, null);
  return response.data;
};

// api/summaryApi.ts

interface FileResponse {
  blob: Blob;
  filename: string;
}

/**
 * 获取 SEA 汇总文件（含文件名）
 */
export const fetchSeaSummaryFile = async (tenderId: string): Promise<FileResponse> => {
  const response = await api.get(`/tenders/${tenderId}/summaries/sea`, {
    responseType: 'blob',
  });

  const filename = parseFilenameFromHeader(response.headers['content-disposition'])
    || '海运招标汇总表.xlsx';

  return {
    blob: response.data,
    filename,
  };
};

/**
 * 获取 PP管件 汇总文件（含文件名）
 */
export const fetchPipeSummaryFile = async (tenderId: string): Promise<FileResponse> => {
  const response = await api.get(`/tenders/${tenderId}/summaries/pipe`, {
    responseType: 'blob',
  });

  const filename = parseFilenameFromHeader(response.headers['content-disposition'])
    || 'PP管件招标汇总表.xlsx';

  return {
    blob: response.data,
    filename,
  };
};

export const createSteelSummary = async (tenderId: string): Promise<POSTResponse> => {
  const response = await api.post<POSTResponse>(`/tenders/${tenderId}/summaries/steel`, null);
  return response.data;
};


export const fetchSteelSummaryFile = async (tenderId: string): Promise<FileResponse> => {
  const response = await api.get(`/tenders/${tenderId}/summaries/steel`, {
    responseType: 'blob',
  });

  const filename = parseFilenameFromHeader(response.headers['content-disposition'])
    || '钢材招标汇总表.xlsx';

  return {
    blob: response.data,
    filename,
  };
};

export const downloadSteelSummaryFile = async (tenderId: string): Promise<void> => {
  const { blob, filename } = await fetchSteelSummaryFile(tenderId);
  triggerDownload(blob, filename);
};

export const createElectricalSummary = async (tenderId: string): Promise<POSTResponse> => {
  const response = await api.post<POSTResponse>(`/tenders/${tenderId}/summaries/electrical`, null);
  return response.data;
};

export const fetchElectricalSummaryFile = async (tenderId: string): Promise<FileResponse> => {
  const response = await api.get(`/tenders/${tenderId}/summaries/electrical`, {
    responseType: 'blob',
  });

  const filename = parseFilenameFromHeader(response.headers['content-disposition'])
    || '电气招标汇总表.xlsx';

  return {
    blob: response.data,
    filename,
  };
};

export const downloadElectricalSummaryFile = async (tenderId: string): Promise<void> => {
  const { blob, filename } = await fetchElectricalSummaryFile(tenderId);
  triggerDownload(blob, filename);
};

// 解析文件名工具函数
const parseFilenameFromHeader = (header?: string): string | null => {
  if (!header) return null;
  const match = header.match(/filename\*=UTF-8''(.+)/i);
  if (match && match[1]) {
    try {
      return decodeURIComponent(match[1]);
    } catch (e) {
      console.warn('Failed to decode filename:', match[1]);
      return match[1];
    }
  }
  return null;
};

// 基于 FileResponse 的下载函数
export const downloadSeaSummaryFile = async (tenderId: string): Promise<void> => {
  const { blob, filename } = await fetchSeaSummaryFile(tenderId);
  triggerDownload(blob, filename);
};

export const downloadPipeSummaryFile = async (tenderId: string): Promise<void> => {
  const { blob, filename } = await fetchPipeSummaryFile(tenderId);
  triggerDownload(blob, filename);
};

// 触发下载
const triggerDownload = (blob: Blob, filename: string) => {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);
};